use crate::entity::{fetch_page, Page, PaginationOptions};
use crate::wechat::entity::wechat_user_type::{WechatUserType, WechatUserTypePageReq};
use crate::SQLX;
use anyhow::anyhow;
use ormlite::sqlite::Sqlite;
use ormlite::Model;
use salvo::{Depot, Request};
use sqlx::QueryBuilder;

pub struct WechatUserTypeService {}


impl WechatUserTypeService {
    pub async fn insert(request: &mut Request, depot: &mut Depot) -> anyhow::Result<()> {
        let body = request.parse_json::<WechatUserType>().await?;
        let sqlx = SQLX.get().ok_or(anyhow!("db error"))?;
        //let db = sqlx.acquire().await?;
        body.insert(sqlx).await?;
        Ok(())
    }

    pub async fn edit(request: &mut Request, depot: &mut Depot) -> anyhow::Result<()> {
        let body = request.parse_json::<WechatUserType>().await?;
        let sqlx = SQLX.get().ok_or(anyhow!("db error"))?;
        //let db = sqlx.acquire().await?;
        body.update_all_fields(sqlx).await?;
        Ok(())
    }


    pub async fn cursor(request: &mut Request, depot: &mut Depot) -> anyhow::Result<Vec<WechatUserType>> {
        let wechat_user_page_req = request.parse_json::<WechatUserTypePageReq>().await?;
        let sqlx = SQLX.get().ok_or(anyhow!("db error"))?;
        //let db = sqlx.acquire().await?;
        let mut wrapper = WechatUserType::select();
        if let Some(user_name) = wechat_user_page_req.name {
            wrapper = wrapper.where_("name like '%?%'").bind(user_name);
        }
        wrapper = wrapper.where_("type_id > ?").bind(wechat_user_page_req.type_id).where_("state =?").bind(1);
        let result: Vec<WechatUserType> = wrapper.fetch_all(sqlx).await?;
        Ok(result)
    }

    pub async fn page(request: &mut Request, depot: &mut Depot) -> anyhow::Result<Page<WechatUserType>> {
        let wechat_user_page_req = request.parse_json::<WechatUserTypePageReq>().await?;
        let mut builder: QueryBuilder<Sqlite> = QueryBuilder::new("select * from wechat_user_type where 1=1 ");

        if let Some(user_name) = wechat_user_page_req.name {
            builder.push(format!(" and name like '%{}%' ", user_name));
        }
        let sql = builder.sql();
        let options = PaginationOptions { page_no: wechat_user_page_req.page_no, page_size: wechat_user_page_req.page_size };
        let page: Page<WechatUserType> = fetch_page(sql, &options).await?;
        Ok(page)
    }
}